//
//  NetWorkCallBack.m
//  GasCome
//
//  Created by ykj on 2018/5/30.
//  Copyright © 2018年 depu. All rights reserved.
//

#import "NetWorkCallBack.h"
#import "LoginModel.h"
#import "BaseTabBarVC.h"
//#import <SSKeychain.h>
@implementation NetWorkCallBack

- (NSURLSessionDataTask *)dataTaskWithRequest:(NSMutableURLRequest *)request
                               uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgressBlock
                             downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgressBlock
                            completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject,  NSError * _Nullable error))completionHandler {
    
    void (^__block authFailBlock)(NSURLResponse *response, id responseObject, NSError *error) = ^(NSURLResponse *response, id responseObject, NSError *error)
    {
        NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
        if([httpResponse statusCode] == 401){

            NSLog(@"accessToken过期");
            
            NSLog(@"错误:显示重新登录页面2");
            [CommonFunc showLogin:nil];
                //调用refreshAccesstoken方法，刷新access token。
               /* [self refreshAccessToken:^(NSDictionary * _Nullable data) {
                    //如果access token过期，返回错误，调用此block

                    if([[data objectForKey:@"code"] intValue]==200){
                        NSLog(@"accessToken过期, 使用refreshToken重新刷新成功");

                        NSDictionary *dataDic = data[@"data"];

                        LoginModel *model = UserAccountManager.shared.user;
                        model.access_token = dataDic[@"access_token"];
                        model.refresh_token = dataDic[@"refresh_token"];
                        [UserAccountManager.shared saveUser:model];

                        [request setValue:dataDic[@"access_token"] forHTTPHeaderField:@"X-Api-Key"];
                        NSURLSessionDataTask *stask = [super dataTaskWithRequest:request uploadProgress:uploadProgressBlock downloadProgress:downloadProgressBlock completionHandler:completionHandler];
                        [stask resume];

                    }else{
                          dispatch_async(dispatch_get_main_queue(), ^{
      
                              if (UserAccountManager.shared.is_login) {
                                  LoginModel *model1 = UserAccountManager.shared.user;
                                  LoginModel *model = [[LoginModel alloc] init];
//                                  model1.access_token = @"";
                                  model1.refresh_token = model1.refresh_token;
                                  [UserAccountManager.shared saveUser:model];
                                  [CommonFunc showLogin:nil];

                              } else {
                                  NSLog(@"错误:显示重新登录页面2");
                                  [CommonFunc 2:nil];
                              }

                        });
                        completionHandler(response, responseObject, error);
                    }
                }];*/
        }else{
            NSLog(@"no auth error");
            completionHandler(response, responseObject, error);
        }
    };
    
    NSURLSessionDataTask *stask = [super dataTaskWithRequest:request uploadProgress:uploadProgressBlock downloadProgress:downloadProgressBlock completionHandler:authFailBlock];
    
    return stask;
}
/*
 *获取新的token的方法。如何获取可以自定义，我这里用了AFNetWorking的AFHTTPRequestOperation类
 */
-(void)refreshAccessToken:(void(^)(NSDictionary * _Nullable data))refresh {

    LoginModel *model = UserAccountManager.shared.user;

    NSURLSession *session = [NSURLSession sharedSession];
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/merapi/v1/site/refresh",localhttp]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    request.HTTPBody = [[NSString stringWithFormat:@"refresh_token=%@&group=ios", model.refresh_token] dataUsingEncoding:NSUTF8StringEncoding];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        refresh(jsonDict);
    }];
    [dataTask resume];

}

#pragma mark - properties

- (id<UIApplicationDelegate>)appDelegate
{
    return [UIApplication sharedApplication].delegate;
}

- (UIWindow *)rootWindow
{
    UIWindow *result = nil;
    
    do {
        if ([self.appDelegate respondsToSelector:@selector(window)]) {
            result = [self.appDelegate window];
        }
        
        if (result) {
            break;
        }
    } while (NO);
    
    return result;
}

- (NSURL *)getParamsWithUrlString:(NSString*)urlString withToken:(NSString *)token{
    NSArray *allElements = [urlString componentsSeparatedByString:@"?"];
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];//待set的参数字典
    //有参数或者?后面为空
    NSString*myUrlString = allElements[0];
    NSString*paramsString = allElements[1];
    //获取参数对
    NSArray*paramsArray = [paramsString componentsSeparatedByString:@"&"];
    if(paramsArray.count>=2) {
        for(NSInteger i =0; i < paramsArray.count; i++) {
            NSString *singleParamString = paramsArray[i];
            
            NSArray *singleParamSet = [singleParamString componentsSeparatedByString:@"="];
            if(singleParamSet.count==2) {
                NSString*key = singleParamSet[0];
                NSString*value = singleParamSet[1];
                if(key.length>0|| value.length>0) {
                    [params setObject:value.length>0?value:@""forKey:key.length>0?key:@""];
                }
            }
        }
    }else if(paramsArray.count==1) {
        NSString*singleParamString = paramsArray[0];
        NSArray*singleParamSet = [singleParamString componentsSeparatedByString:@"="];
        if(singleParamSet.count==2) {
            NSString*key = singleParamSet[0];
            NSString*value = singleParamSet[1];
            if(key.length>0|| value.length>0) {
                [params setObject:value.length>0?value:@""forKey:key.length>0?key:@""];
            }
        }else{
            //问号后面啥也没有 xxxx?  无需处理
        }
    }
    [params setValue:token forKey:@"accessToken"];
    NSString *url = [NSString stringWithFormat:@"%@?",myUrlString];
    
    NSArray *keys = [params allKeys];
    for (int i = 0; i < [keys count]; i ++) {
        id key = [keys objectAtIndex:i];
        id obj = [params objectForKey:key];
        if(i==0){
            url = [NSString stringWithFormat:@"%@%@=%@",url,key,obj];
        }else{
            url = [NSString stringWithFormat:@"%@&%@=%@",url,key,obj];
        }
    }
    
    return [NSURL URLWithString:url];
}
@end
